import { Component,ViewChild } from '@angular/core';
import { NavController, LoadingController, Slides } from 'ionic-angular';
import { HttpsService } from "../../providers/http.service";
// import { StorageService } from '../../providers/StorageService';
// import { MySlide } from '../../components/my-slide/my-slide';
// import {ComponentsModule} from "../../components/components.module";
import { ThemeableBrowser, ThemeableBrowserOptions, ThemeableBrowserObject} from '@ionic-native/themeable-browser';
import { NewsDetailPage } from '../news-detail/news-detail';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('contentSlides') contentSlides: Slides;
  @ViewChild('menuSlides') menuSlides: Slides;

  pageIndex:number = 0;
  pageContent:string;
  pageSlides:string[] = ["头条", "社会", "国内", "国际", "娱乐", "体育", "军事", "科技", "财经", "时尚"];
  pageHttpSlides:string[] = ["top", "shehui", "guonei", "guoji", "yule", "tiyu", "junshi", "keji", "caijing", "shishang"];
  // homeArticles = {"top":[],"shehui":[],"guonei":[],"guoji":[],"yule":[],"tiyu":[],"junshi":[],"keji":[],"caijing":[],"shishang":[]};
  homeArticles = [];
  temphHomeArticles = [];//存储单页数据

  hostURL = 'http://v.juhe.cn/toutiao/index';
  APPKEY:string = '17702324002789c3101fab2a1cc280b7';
  public picture:string;
  public loading; //加载弹框

  selectedIndex:number = 0;

  constructor(public navCtrl: NavController, private http:HttpsService, private loadCtrl:LoadingController, private themeableBrowser: ThemeableBrowser) {
    this.loading = this.loadCtrl.create({
      content:"加载中..."
    })
    for(var i = 0; i < this.pageSlides.length; i++) {
      this.homeArticles.push([]);
    }
    this.loading.present();
    this.setPageContent();//设置默认显示
    this.getHttpService(this.pageContent);
  }
  //页面初始化执行次操作，推荐将复杂的东西要放在ngOnInit()方法里，不要放在构造方法里
  ngOnInit() {
    //ionic 2.0正式版本中，请删除mySlideOptions相关代码。
    // this.mySlideOptions = {
    //   loop: false,
    //   autoplay: false,
    //   initialSlide: 0,
    //   pager: false,
    //   slidesPerView: 5,
    //   paginationHide: true,
    //   paginationClickable: true
    // };
  }

  setPageContent() {
    this.pageContent = this.pageHttpSlides[this.pageIndex];
  }
  getHttpService(itemName) {
    let url = this.hostURL+ "?type=" + itemName + "&key=" + this.APPKEY;
    console.log("res====="+url);
    this.http.get(url, null, res => {
      // 网络请求成功
      if(res.result == null) {
        this.loading.dismiss();
        this.testData();
        return;
      }
      let alldata = res.result.data;
      this.temphHomeArticles = this.homeArticles[this.pageIndex];
      this.temphHomeArticles = [];
      console.log("res====="+alldata.length);
      for(var i = 0; i < alldata.length; i++){
        var type = 1;
        if(i>10) {
          type = 2;
        }
        this.temphHomeArticles.push({
          title:alldata[i].title,
          picture:alldata[i].thumbnail_pic_s03,//图片3
          author_name: alldata[i].author_name,
          date: alldata[i].date,
          url: alldata[i].url,
          type:type
        })
      }
      this.homeArticles[this.pageIndex] = this.temphHomeArticles;
      // console.log("res====="+this.temphHomeArticles);
      this.loading.dismiss();
    }, err => {
      // 网络请求出现错误
      console.log('error.....')
    })
  }
  //下拉刷新
  doRefresh(refresher) {
    console.log('Begin async operation', refresher);
    setTimeout(() => {
      console.log('Async operation has ended');
      this.getNewArticle(this.pageContent,1);
      refresher.complete();
    }, 1000);
  }
  //上拉加载
  doInfinite(infiniteScroll) {
    console.log('Begin async operation', infiniteScroll);
    setTimeout(() => {
      // for (let i = 0; i < 30; i++) {
      //   this.items.push( this.items.length );
      // }
      console.log('Async operation has ended');
      this.getNewArticle(this.pageContent,2);
      infiniteScroll.complete();

      this.temphHomeArticles = this.homeArticles[this.pageIndex];
      if (this.temphHomeArticles.length%20 != 0) {
        infiniteScroll.enable(false);   //没有数据的时候隐藏 ion-infinate-scroll
      }
    }, 1000);
  }
  testData() {
    this.temphHomeArticles = this.homeArticles[this.pageIndex];
    this.temphHomeArticles = [];
    for(var i = 0; i < 20; i++){
      var type = 1;
      if(i>10) {
        type = 2;
      }
      this.temphHomeArticles.push({
        title:"shahsfahvsdvh嫁女四v你贾女士的v你假i佳佳及v家v就",
        picture:"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1065467524,1476957344&fm=26&gp=0.jpg",//图片3
        author_name: '小学按钮',
        date: '今天',
        url: '',
        type:type
      })
    }
    this.homeArticles[this.pageIndex] = this.temphHomeArticles;
    // console.log("res====="+this.temphHomeArticles);
    // this.loading.dismiss();
  }
  testData2(refreshType) {
    this.temphHomeArticles = this.homeArticles[this.pageIndex];
    for(var i = 0; i < 20; i++){
      var type = 1;
      if(refreshType == 1) {
        this.temphHomeArticles.unshift({
          title:"下拉刷新hahsfahvsdvh嫁女四v你贾女士的v你假i佳佳及v家v就",
          picture:"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1065467524,1476957344&fm=26&gp=0.jpg",//图片3
          author_name: '小学按钮haha',
          date: '今天',
          url: '',
          type:type
        })
      } else {
        this.temphHomeArticles.push({
          title:"上拉加载shahsfahvsdvh嫁女四v你贾女士的v你假i佳佳及v家v就",
          picture:"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1065467524,1476957344&fm=26&gp=0.jpg",//图片3
          author_name: '小学按钮kkkk',
          date: '今天',
          url: '',
          type:type
        })
      }
      
    }
    this.homeArticles[this.pageIndex] = this.temphHomeArticles;
  }

  //获取新闻信息 refreshType:1下拉加载 2上拉刷新
  getNewArticle(itemName, refreshType) {
    let url = this.hostURL+ "?type=" + itemName + "&key=" + this.APPKEY;
    this.http.get(url, null,res => {
      // 网络请求成功
      if(res.result == null) {
        this.loading.dismiss();
        this.testData2(refreshType);
        return;
      }
      this.temphHomeArticles = this.homeArticles[this.pageIndex];
      let alldata = res.result.data;
      console.log("res====="+alldata.length);
      for(var i = 0; i < alldata.length; i++){
        var type = 1;
        if(refreshType == 1) {
          this.temphHomeArticles.unshift({
            title: alldata[i].title,//标题
            picture: alldata[i].thumbnail_pic_s03,//图片3
            author_name: alldata[i].author_name,
            date: alldata[i].date,
            url: alldata[i].url,
            type:type
          })
        } else {
          this.temphHomeArticles.push({
            title: alldata[i].title,//标题
            picture: alldata[i].thumbnail_pic_s03,//图片3
            author_name: alldata[i].author_name,
            date: alldata[i].date,
            url: alldata[i].url,
            type:type
          })
        }
        
      }
      this.homeArticles[this.pageIndex] = this.temphHomeArticles;
    }, err => {
      // 网络请求出现错误
      console.log('error.....')
    })
  }
  //点击标题
  onSlideClick(index) {
    this.contentSlides.slideTo(index, 500, false); //新闻页滑动
    this.requestData(index);
  }
  //滑动列表
  slideChanged() {
    let index = this.contentSlides.getActiveIndex();
    if(index > 2) { //菜单滑动
      this.menuSlides.slideTo(index-2, 500, false);
    } else {
      this.menuSlides.slideTo(0, 500, false);
    }
    this.requestData(index);
  }
  requestData(currentIndex) {
    this.pageIndex = currentIndex;
    this.setPageContent();
    let currArr = this.homeArticles[this.pageIndex];
    console.log("currArr=="+currArr)
    // this.getHttpService(this.pageContent);
    if(!currArr || currArr.length == 0) {
      this.loading = this.loadCtrl.create({
        content: '加载中...',
      });
      this.loading.present();
      this.getHttpService(this.pageContent);
    } else {
      this.temphHomeArticles = this.homeArticles[this.pageIndex];
    }
  }
  //打开详情页
  showArticles(event, url) {
    let options:ThemeableBrowserOptions = {
      statusbar: {
        color: '#ffffffff'
      },
      toolbar: {
        height: 44,
        color: '#f0f0f0ff'
      },
      // title: {
      //   color: '#003264ff',
      //   showPageTitle: true
      // },
      backButton: {
        image: 'back',
        imagePressed: 'back_pressed',
        align: 'left',
        event: 'backPressed'
      },
      // forwardButton: {
      //   image: 'forward',
      //   imagePressed: 'forward_pressed',
      //   align: 'left',
      //   event: 'forwardPressed'
      // },
      closeButton: {
        image: 'close',
        imagePressed: 'close_pressed',
        align: 'left',
        event: 'closePressed'
      },
      // customButtons: [
      //   {
      //     image: 'share',
      //     imagePressed: 'share_pressed',
      //     align: 'right',
      //     event: 'sharePressed'
      //   }
      // ],
      menu: {
        image: 'menu',
        imagePressed: 'menu_pressed',
        title: 'Test',
        cancel: 'Cancel',
        align: 'right',
        items: [
          {
            event: 'sharePressed',
            label: '分享'
          },
          {
            event: 'savePressed',
            label: '收藏'
          }
        ]
      },
      backButtonCanClose: true
    };

    const browser: ThemeableBrowserObject = this.themeableBrowser.create(url, '_blank', options);
    browser.on('sharePressed').subscribe((data)=>{
      alert('share');
    }, (err)=>{
      alert('share:error');
      console.error('onError');
    })
    browser.on('savePressed').subscribe((data)=>{

    }, (err)=>{
      
    })
    /** 传参
     * @param msg 子传父
     */
    // let action = (msg)=>{
    //   return new Promise((resolve, reject)=>{
    //     if(msg!=undefined) {
    //       console.log('get son data:'+msg);
    //       resolve('ok');
    //     } else {
    //       reject(Error('error'));
    //     }
    //   })
    // }
    
    /** 父传子
     * 1.push 传参
     * 2.回到当前界面所在的tab界面
     * 3.回到第一个tab界面
     *  */
    // this.navCtrl.push(NewsDetailPage, { "params": item});
    // this.navCtrl.popToRoot();// 返回当前界面所在的tab界面
    // this,this.navCtrl.parent.select(0);
  }
}
 
